'use strict';
var EventEmitter = require('events').EventEmitter;
var AppDispatcher = require('../dispatcher/AppDispatcher');
var ActionTypes = require('../constants/WorryConstants').ActionTypes;
var assign = require('object-assign');
var DB=require("./Db");
var Api=require("../utils/Api.js");

var modalVisible=false;
var CHANGE_EVENT = 'change';
var AskStore = assign({}, EventEmitter.prototype, {
  initState:function(){
    return {
            "id": 0,
            "uid": 0,
            "head": "",
            "name": "",
            "content": "",
            "count": 0,
            "time": "",
            "hits": 0,
            "favTotalNum": 0,
            "isFav": true
        };
  },
  emitChange: function() {
    this.emit(CHANGE_EVENT);
  },

  /**
   * @param {function} callback
   */
  addChangeListener: function(callback) {
    this.on(CHANGE_EVENT, callback);
  },

  /**
   * @param {function} callback
   */
  removeChangeListener: function(callback) {
    this.removeListener(CHANGE_EVENT, callback);
  },
  askInit:function(){
    var that=this;
    DB.ask.get({name:'ask'},function(rs){
      if(!Api.isEmpty(rs))
        return false;
      that.fetchAsk(null);
    });
    
  },

  fetchAsk:function(cb){
    DB.ask.get({name:'ask'},function(rs){
      var page=1;
      if(!Api.isEmpty(rs)){
        page=rs[0].page+1;

      }
      Api.request({page:page},'ask/get-ask-filter-list',function(trs){
        console.log(page);
        if(trs.code!=0)
          return false;

        if(Api.isEmpty(rs)){
          DB.ask.add({name:'ask',page:1,data:trs.data.array_name},function(){cb()});
        }
        else{
          var tmpData=rs[0].data.concat(trs.data.array_name);
          DB.ask.update({name:'ask'},{data:tmpData,page:page},function(){cb()})
        }
          
        cb();
      });
    })
    
  },
  
  update:function(cb){
    
    DB.ask.get({name:'ask'},function(rs){
        cb(rs[0].data) 
      })

  }

});

AskStore.dispatchToken = AppDispatcher.register(function(action) {

  switch(action.type) {

    case ActionTypes.FETCH_MORE:
      AskStore.fetchAsk(function(){
        console.log('fetch_more')
        AskStore.emitChange();
      });

      break;
    
  }

});


module.exports = AskStore;
